package com.molichuxing.gateway.bff.order.services.impl;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.gateway.bff.order.convertor.Convert;
import com.molichuxing.gateway.bff.order.entity.request.create.OrderEnterpriseDeliveryCreateVo;
import com.molichuxing.gateway.bff.order.entity.request.create.OrderEnterpriseReturnCreateVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderEnterpriseCarReturnVo;
import com.molichuxing.gateway.bff.order.services.OrderEnterpriseCarHandoverBffService;
import com.molichuxing.services.business.dto.request.create.OrderEnterpriseDeliveryCreateBizDto;
import com.molichuxing.services.business.dto.request.create.OrderEnterpriseReturnCreateBizDto;
import com.molichuxing.services.business.service.CarBizService;
import com.molichuxing.services.business.service.EnterpriseCarHandoverBizService;
import com.molichuxing.services.infrastructure.dto.request.create.ContractEnterpriseCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.IovFenceBindingCreateDto;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.ContractEnterpriseTypeEnum;
import com.molichuxing.services.property.StockCarCarStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

@Service("orderEnterpriseCarHandoverBffService")
public class OrderEnterpriseCarHandoverBffServiceImpl implements OrderEnterpriseCarHandoverBffService {
    private static final Logger logger = LoggerFactory.getLogger(OrderEnterpriseCarHandoverBffServiceImpl.class);

    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private CarService carService;
    @Resource
    private EnterpriseCarHandoverBizService enterpriseCarHandoverBizService;
    @Resource
    private ContractEnterpriseService contractEnterpriseService;
    @Resource
    private CarBizService carBizService;
    @Resource
    private IovFenceService iovFenceService;

    @Resource
    private StockCarService stockCarService;
    @Resource
    private EnterpriseCarHandoverService enterpriseCarHandoverService;

    @Resource
    private EntrepotStorageService entrepotStorageService;


    /**
     * 退租
     *
     * @param orderEnterpriseReturnCreateVo
     * @return
     */
    @Override
    public Boolean createOrderEnterpriseReturn(OrderEnterpriseReturnCreateVo orderEnterpriseReturnCreateVo) throws Exception {
        OrderEnterpriseReturnCreateBizDto orderEnterpriseReturnCreateBizDto = Convert.toOrderEnterpriseReturnCreateBizDto(orderEnterpriseReturnCreateVo);
        enterpriseCarHandoverBizService.createOrderEnterpriseReturn(orderEnterpriseReturnCreateBizDto);

        modifyExclusivelReturnCar(orderEnterpriseReturnCreateVo);
        ContractEnterpriseCreateDto contractEnterpriseCreateDto = Convert.toContractEnterpriseCreateDto(orderEnterpriseReturnCreateVo);
        contractEnterpriseService.createContract(contractEnterpriseCreateDto);
        return true;
    }

    /**
     * 修改车辆信息
     *
     * @param orderEnterpriseReturnCreateVo
     * @return
     * @throws Exception
     */
    private boolean modifyExclusivelReturnCar(OrderEnterpriseReturnCreateVo orderEnterpriseReturnCreateVo) throws Exception {
        Integer carId = orderEnterpriseReturnCreateVo.getCarId();
        String vin = orderEnterpriseReturnCreateVo.getVin();
        Integer fenceId = orderEnterpriseReturnCreateVo.getFenceId();
        CarModifyDto carModifyDto = Convert.toCarModifyDto(orderEnterpriseReturnCreateVo);
        if (carService.modify(carModifyDto) < 1) {
            logger.error("[createOrderEnterpriseReturn]车辆({})退租修改车辆信息失败", carId);
            throw new BizException("退租失败");
        }
        if (!stockCarService.modifyCarStatus(carId, StockCarCarStatusEnum.FOR_RENT.getValue())) {
            logger.error("[createOrderEnterpriseReturn]车辆({})退租修改库存信息失败", carId);
            throw new BizException("退租失败");
        }

        IovFenceBindingCreateDto createDto = new IovFenceBindingCreateDto();
        createDto.setListVin(Arrays.asList(vin));
        createDto.setFenceId(Long.valueOf(fenceId));
        try{
            iovFenceService.addBindingFence(createDto);
        }catch (Exception e){
            throw new BizException(ResponseCodeEnum.IOV_ERROR.getCode(),"电子围栏绑定失败，请到茉莉车辆监控平台处理");
        }
        return true;
    }

    /**
     * 退租详情
     *
     * @param carHandoverId
     * @return
     */
    @Override
    public OrderEnterpriseCarReturnVo getOrderEnterpriseReturnDetail(Integer carHandoverId) {
        EnterpriseCarHandoverDto enterpriseCarHandoverDto = enterpriseCarHandoverService.getById(carHandoverId);
        if (null == enterpriseCarHandoverDto) {
            return null;
        }

        Integer carId = enterpriseCarHandoverDto.getCarId();
        Integer fenceId = enterpriseCarHandoverDto.getFenceId();
        Integer handoverStockId = enterpriseCarHandoverDto.getHandoverStockId();
        Long orderCode = enterpriseCarHandoverDto.getOrderCode();

        CarDto carDto = carService.getCarById(carId);
        IovFenceDto iovFenceDto = iovFenceService.getFenceById(fenceId);
        EntrepotStorageDto entrepotStorageDto = entrepotStorageService.getEntrepotStorage(handoverStockId);
        ContractEnterpriseDto contractEnterpriseDto = contractEnterpriseService.getContractByOrderCode(orderCode, carId, ContractEnterpriseTypeEnum.RETURN_CAR_CONTRACT);

        return Convert.toOrderEnterpriseCarReturnVo(enterpriseCarHandoverDto, carDto, iovFenceDto, entrepotStorageDto, contractEnterpriseDto);
    }

    /**
     * 交车
     *
     * @param orderEnterpriseDeliveryCreateVo
     * @return
     */
    @Override
    public Boolean createOrderEnterpriseDelivery(OrderEnterpriseDeliveryCreateVo orderEnterpriseDeliveryCreateVo) throws Exception {
        OrderEnterpriseDeliveryCreateBizDto orderEnterpriseReturnCreateBizDto = Convert.toOrderEnterpriseDeliveryCreateBizDto(orderEnterpriseDeliveryCreateVo);
        enterpriseCarHandoverBizService.createOrderEnterpriseDelivery(orderEnterpriseReturnCreateBizDto);

        modifyExclusivelDeliveryCar(orderEnterpriseDeliveryCreateVo);
        ContractEnterpriseCreateDto contractEnterpriseCreateDto = Convert.toContractEnterpriseCreateDto(orderEnterpriseDeliveryCreateVo);
        contractEnterpriseService.createContract(contractEnterpriseCreateDto);
        return true;
    }

    /**
     * 修改车辆信息
     *
     * @param orderEnterpriseDeliveryCreateVo
     * @return
     * @throws Exception
     */
    private boolean modifyExclusivelDeliveryCar(OrderEnterpriseDeliveryCreateVo orderEnterpriseDeliveryCreateVo) throws Exception {
        Integer carId = orderEnterpriseDeliveryCreateVo.getCarId();
        String vin = orderEnterpriseDeliveryCreateVo.getVin();
        CarModifyDto carModifyDto = Convert.toCarModifyDto(orderEnterpriseDeliveryCreateVo);
        if (carService.modify(carModifyDto) < 1) {
            logger.error("[modifyExclusivelDeliveryCar]交车，车辆({})修改车辆信息失败", carId);
            throw new BizException("交车失败");
        }

        if (!stockCarService.modifyCarStatus(carId, StockCarCarStatusEnum.RENTED.getValue())) {
            logger.error("[modifyExclusivelDeliveryCar]交车，车辆({})修改库存信息失败", carId);
            throw new BizException("交车失败");
        }

        try{
            iovFenceService.deleteAllFence(vin);
        }catch (Exception e){
            throw new BizException(ResponseCodeEnum.IOV_ERROR.getCode(),"电子围栏解绑失败，请到茉莉车辆监控平台处理");
        }
        return true;
    }

}
